package cn.wolfcode.wms.web.controller;

import cn.wolfcode.wms.domain.Product;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IBrandService;
import cn.wolfcode.wms.service.IProductService;
import cn.wolfcode.wms.util.JSONResult;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.StringUtil;
import cn.wolfcode.wms.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

@Controller
@RequestMapping("product")
public class ProductController {
    @Autowired
    private IProductService productService;
    @Autowired
    private IBrandService brandService;
    @Autowired
    private ServletContext ctx;
    @RequestMapping("list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){

        PageResult result = productService.queryForList(qo);

        model.addAttribute("result",result);
        return "product/list";
    }

    @RequestMapping("listView")
    public String listView(Model model, @ModelAttribute("qo") QueryObject qo){
        qo.setPageSize(20);//故意写死
        PageResult result = productService.queryForList(qo);

        model.addAttribute("result",result);
        return "product/listView";
    }

    @RequestMapping("input")
    public String input(Model model,Long id){
        model.addAttribute("brands",brandService.selectall());
        if (id != null) {
            Product entity = productService.get(id);
            model.addAttribute("entity",entity);
        }
        return "product/input";
    }

    @ResponseBody
    @RequestMapping("saveOrUpdate")
    public Object saveOrUpdate(Product entity, MultipartFile pic) {
        //处理图片
        if (pic != null && pic.getContentType().startsWith("image") && pic.getSize() > 0) {
            //是否需要删除旧的图片
            if (entity.getImagePath()!=null&&!entity.getImagePath().equals("")) {
                UploadUtil.deleteFile(ctx, entity.getImagePath());
            }
            //符合上传的图片要求
            String path = UploadUtil.upload(pic, ctx.getRealPath("/upload"));
            entity.setImagePath(path);
        }
        productService.saveOrUpdate(entity);
        return new JSONResult();
    }
    @ResponseBody
    @RequestMapping("delete")
    public Object delete(Long id){

       productService.delete(id);
        JSONResult json = new JSONResult();
        return json;
    }
}
